package com.github.niefy.modules.wxma.manage;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.github.niefy.common.utils.R;
import com.github.niefy.modules.wxma.entity.MaAccount;
import com.github.niefy.modules.wxma.service.MaAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * 小程序账号
 *
 * @author niefy
 * @date 2020-06-17 13:56:51
 */
@RestController
@RequestMapping("/manage/maAccount")
@Api(tags = {"小程序账号-管理后台"})
public class MaAccountManageController {
    @Autowired
    private MaAccountService wxMaAccountService;

    @Autowired
    private WxMaService wxMaService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @RequiresPermissions("wx:maaccount:list")
    @ApiOperation(value = "列表")
    public R list() {
        List<MaAccount> list = wxMaAccountService.list();
        return R.ok().put("list", list);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{appid}")
    @RequiresPermissions("wx:maaccount:info")
    @ApiOperation(value = "详情")
    public R info(@PathVariable("id") String appid) {
        MaAccount wxMaAccount = wxMaAccountService.getById(appid);

        return R.ok().put("wxMaAccount", wxMaAccount);
    }


    /**
     * 信息
     */
    @PostMapping("/updateAccessToken")
    @RequiresPermissions("wx:maaccount:updateAccessToken")
    @ApiOperation(value = "更新accessToken")
    public R updateAccessToken(@RequestBody String[] appids) throws WxErrorException {
        Arrays.asList(appids).forEach(appid -> {
            try {
                this.wxMaService.switchoverTo(appid);
                //更新accessToken
                this.wxMaService.getAccessToken(true);
            } catch (WxErrorException e) {
                e.getError();
                return;
            }

        });

        return R.ok();

    }


    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresPermissions("wx:maaccount:save")
    @ApiOperation(value = "保存")
    public R save(@RequestBody MaAccount wxMaAccount) {
        wxMaAccountService.save(wxMaAccount);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @RequiresPermissions("wx:maaccount:delete")
    @ApiOperation(value = "删除")
    public R delete(@RequestBody String[] appids) {
        wxMaAccountService.removeByIds(Arrays.asList(appids));

        return R.ok();
    }

}
